<template>
  <div class="work-reporting-container">
    <!-- 页面标题和搜索栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">报工</h2>
        <el-input
          v-model="searchKeyword"
          placeholder="请选择工序名称"
          clearable
          style="width: 250px; margin-left: 20px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="header-actions">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button type="primary" @click="toggleAdvancedSearch">高级查询</el-button>
        <el-button type="primary" @click="handleAdd" class="add-btn">
          <el-icon><Plus /></el-icon>新增报工
        </el-button>
      </div>
         </div>

     <!-- 高级查询面板（内联展开式） -->
     <div v-show="showAdvancedSearch" class="advanced-search-panel">
       <el-form :model="advancedSearchForm" label-width="120px" class="advanced-search-form">
         <el-row :gutter="20">
           <el-col :span="8">
             <el-form-item label="工序名称">
               <el-input v-model="advancedSearchForm.taskName" placeholder="请输入工序名称" clearable />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="产品编号">
               <el-input v-model="advancedSearchForm.productCode" placeholder="请输入产品编号" clearable />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="产品名称">
               <el-input v-model="advancedSearchForm.productName" placeholder="请输入产品名称" clearable />
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="8">
             <el-form-item label="工序状态">
               <el-select v-model="advancedSearchForm.taskStatus" placeholder="请选择工序状态" clearable style="width: 100%">
                 <el-option label="未开始" value="未开始" />
                 <el-option label="进行中" value="进行中" />
                 <el-option label="已完成" value="已完成" />
               </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="生产人员">
               <el-input v-model="advancedSearchForm.productionPersonnel" placeholder="请输入生产人员" clearable />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="报工数">
               <el-input-number v-model="advancedSearchForm.reportedQuantity" :min="0" :max="999999" style="width: 100%" controls-position="right" />
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="8">
             <el-form-item label="工单">
               <el-input v-model="advancedSearchForm.workOrderNo" placeholder="请输入工单号" clearable />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="单位">
               <el-select v-model="advancedSearchForm.unit" placeholder="请选择单位" clearable style="width: 100%">
                 <el-option v-for="u in unitOptions" :key="u" :label="u" :value="u" />
               </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="良品数">
               <el-input-number v-model="advancedSearchForm.goodQuantity" :min="0" :max="999999" style="width: 100%" controls-position="right" />
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="8">
             <el-form-item label="开始时间">
               <el-date-picker
                 v-model="advancedSearchForm.startTimeRange"
                 type="datetimerange"
                 range-separator="至"
                 start-placeholder="开始时间"
                 end-placeholder="结束时间"
                 format="YYYY-MM-DD HH:mm:ss"
                 value-format="YYYY-MM-DD HH:mm:ss"
                 style="width: 100%"
               />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="结束时间">
               <el-date-picker
                 v-model="advancedSearchForm.endTimeRange"
                 type="datetimerange"
                 range-separator="至"
                 start-placeholder="开始时间"
                 end-placeholder="结束时间"
                 format="YYYY-MM-DD HH:mm:ss"
                 value-format="YYYY-MM-DD HH:mm:ss"
                 style="width: 100%"
               />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="创建时间">
               <el-date-picker
                 v-model="advancedSearchForm.createTimeRange"
                 type="datetimerange"
                 range-separator="至"
                 start-placeholder="开始时间"
                 end-placeholder="结束时间"
                 format="YYYY-MM-DD HH:mm:ss"
                 value-format="YYYY-MM-DD HH:mm:ss"
                 style="width: 100%"
               />
             </el-form-item>
           </el-col>
         </el-row>
         
         <div class="advanced-search-actions">
           <el-button type="primary" @click="handleAdvancedSearch" class="search-btn">
             <el-icon><Search /></el-icon>查询
           </el-button>
           <el-button type="success" @click="resetAdvancedSearch" class="reset-btn">
             <el-icon><Refresh /></el-icon>重置
           </el-button>
           <el-button @click="toggleAdvancedSearch" class="close-btn">
             <el-icon><Close /></el-icon>关闭
           </el-button>
         </div>
       </el-form>
     </div>

     <!-- 数据表格 -->
     <div class="table-container">
             <el-table
         :data="workReportList"
         @row-click="handleRowClick"
         v-loading="loading"
         style="width: 100%; flex: 1;"
         border
         stripe
         highlight-current-row
       >

        <el-table-column prop="workOrderNo" label="工单" width="160" show-overflow-tooltip>
          <template #default="scope">
            <el-link type="primary" @click.stop="openDetail(scope.row)">{{ scope.row.workOrderNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="taskName" label="工序名称" width="100" show-overflow-tooltip>
          <template #default="scope">
            <el-tag 
              :type="getTaskNameTagType(scope.row.taskName)"
              size="small"
            >
              {{ scope.row.taskName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="product" label="产品" width="100" show-overflow-tooltip />
        <el-table-column prop="productCode" label="产品编号" width="130" show-overflow-tooltip />
        <el-table-column prop="productName" label="产品名称" width="130" show-overflow-tooltip />
        <el-table-column prop="productSpec" label="产品规格" width="100" show-overflow-tooltip />
        <el-table-column prop="taskStatus" label="工序状态" width="100" show-overflow-tooltip>
          <template #default="scope">
            <el-tag 
              :type="getTaskStatusTagType(scope.row.taskStatus)"
              size="small"
            >
              {{ scope.row.taskStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="productionPersonnel" label="生产人员" width="100" show-overflow-tooltip />
        <el-table-column prop="reportedQuantity" label="报工数" width="80" />
        <el-table-column prop="unit" label="单位" width="60" />
        <el-table-column prop="goodQuantity" label="良品数" width="80" />
        <el-table-column prop="defectiveQuantity" label="不良品数" width="90" />
        <el-table-column prop="processProgress" label="工序进度" width="100" show-overflow-tooltip />
        <el-table-column prop="startTime" label="开始时间" width="140" show-overflow-tooltip>
          <template #default="scope">
            {{ formatDateTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="140" show-overflow-tooltip>
          <template #default="scope">
            {{ formatDateTime(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="reportDurationHours" label="报工时长(小时)" width="120" />
        <el-table-column prop="reportDurationMinutes" label="报工时长(分钟)" width="120" />
        <el-table-column prop="standardEfficiency" label="标准效率" width="90" />
        <el-table-column prop="actualEfficiency" label="实际效率" width="90" />
        <el-table-column prop="complianceRate" label="达标率" width="90">
          <template #default="scope">
            <span :class="getComplianceRateClass(scope.row.complianceRate)">
              {{ formatComplianceRate(scope.row.complianceRate) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="pricingMethod" label="计价方式" width="100" show-overflow-tooltip>
          <template #default="scope">
            <el-button type="primary" size="small" v-if="scope.row.pricingMethod">
              {{ scope.row.pricingMethod }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="工资单价" width="90" />
        <el-table-column prop="estimatedWage" label="预计工资" width="90" />
        <el-table-column prop="approvalStatus" label="审批状态" width="100" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="success" size="small" v-if="scope.row.approvalStatus">
              {{ scope.row.approvalStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approver" label="审批人" width="100" show-overflow-tooltip />
        <el-table-column prop="reportTime" label="报工时间" width="140" show-overflow-tooltip>
          <template #default="scope">
            {{ formatDateTime(scope.row.reportTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="140" show-overflow-tooltip>
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" show-overflow-tooltip />
        <el-table-column prop="modifier" label="修改人" width="100" show-overflow-tooltip />
        <el-table-column prop="modifyTime" label="修改时间" width="140" show-overflow-tooltip>
          <template #default="scope">
            {{ formatDateTime(scope.row.modifyTime) }}
          </template>
        </el-table-column>
              </el-table>
        
        <!-- 分页组件 - 放在表格内部底部 -->
        <div class="table-pagination">
          <el-pagination
            :current-page="pagination.pageIndex"
            :page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="pagination.totalCount"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            small
          />
        </div>
             </div>

    <!-- 详情抽屉 -->
    <el-drawer
      v-model="showDetailDrawer"
      title="报工详情"
      size="50%"
      :close-on-click-modal="true"
    >
      <div v-if="detailData" class="detail-container">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单">{{ detailData.workOrderNo }}</el-descriptions-item>
          <el-descriptions-item label="工序名称">{{ detailData.taskName }}</el-descriptions-item>
          <el-descriptions-item label="产品">{{ detailData.product }}</el-descriptions-item>
          <el-descriptions-item label="产品编号">{{ detailData.productCode }}</el-descriptions-item>
          <el-descriptions-item label="产品名称">{{ detailData.productName }}</el-descriptions-item>
          <el-descriptions-item label="产品规格">{{ detailData.productSpec }}</el-descriptions-item>
          <el-descriptions-item label="工序状态">{{ detailData.taskStatus }}</el-descriptions-item>
          <el-descriptions-item label="生产人员">{{ detailData.productionPersonnel }}</el-descriptions-item>
          <el-descriptions-item label="报工数">{{ detailData.reportedQuantity }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{ detailData.unit }}</el-descriptions-item>
          <el-descriptions-item label="良品数">{{ detailData.goodQuantity }}</el-descriptions-item>
          <el-descriptions-item label="不良品数">{{ detailData.defectiveQuantity }}</el-descriptions-item>
          <el-descriptions-item label="工序进度">{{ detailData.processProgress }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDateTime(detailData.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDateTime(detailData.endTime) }}</el-descriptions-item>
          <el-descriptions-item label="报工时长(小时)">{{ detailData.reportDurationHours }}</el-descriptions-item>
          <el-descriptions-item label="报工时长(分钟)">{{ detailData.reportDurationMinutes }}</el-descriptions-item>
          <el-descriptions-item label="标准效率">{{ detailData.standardEfficiency }}</el-descriptions-item>
          <el-descriptions-item label="实际效率">{{ detailData.actualEfficiency }}</el-descriptions-item>
          <el-descriptions-item label="达标率">{{ formatComplianceRate(detailData.complianceRate) }}</el-descriptions-item>
          <el-descriptions-item label="计价方式">{{ detailData.pricingMethod }}</el-descriptions-item>
          <el-descriptions-item label="工资单价">{{ detailData.unitPrice }}</el-descriptions-item>
          <el-descriptions-item label="预计工资">{{ detailData.estimatedWage }}</el-descriptions-item>
          <el-descriptions-item label="审批状态">{{ detailData.approvalStatus }}</el-descriptions-item>
          <el-descriptions-item label="审批人">{{ detailData.approver }}</el-descriptions-item>
          <el-descriptions-item label="报工时间">{{ formatDateTime(detailData.reportTime as string) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(detailData.createTime as string) }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ detailData.creator }}</el-descriptions-item>
          <el-descriptions-item label="修改人">{{ detailData.modifier }}</el-descriptions-item>
          <el-descriptions-item label="修改时间">{{ formatDateTime(detailData.modifyTime as string) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>

     <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="showEditDialog"
      :title="isEdit ? '编辑报工' : '报工(新建)'"
      width="1200px"
      :close-on-click-modal="false"
      class="work-report-dialog"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="120px">
        <!-- 基本信息区域 -->
        <div class="form-section">
          <div class="section-header">基本信息</div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="工单" prop="workOrderNo">
                <el-select 
                  v-model="editForm.workOrderNo" 
                  placeholder="请选择工单" 
                  style="width: 100%" 
                  @change="handleWorkOrderChange"
                  :loading="loadingWorkOrders"
                  filterable
                >
                  <el-option
                    v-for="item in workOrderList"
                    :key="item.workOrderNo"
                    :label="`${item.workOrderNo}|${item.workOrderName}`"
                    :value="item.workOrderNo"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工序名称" prop="taskName">
                <el-select 
                  v-model="editForm.taskName" 
                  placeholder="请选择工序名称" 
                  style="width: 100%"
                  :loading="loadingWorkOrders"
                  filterable
                >
                  <el-option
                    v-for="process in processList"
                    :key="process.processId"
                    :label="process.processName"
                    :value="process.processName"
                  />
                </el-select>
                <!-- 调试信息 -->
                <div style="font-size: 12px; color: #999; margin-top: 4px;">
                  用户数量: {{ userList.length }}
                  <span v-if="userList.length > 0">
                    ({{ userList.slice(0, 3).map(u => u.name).join(', ') }}{{ userList.length > 3 ? '...' : '' }})
                  </span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品" prop="product">
                <el-select v-model="editForm.product" placeholder="请选择产品" style="width: 100%">
                  <el-option label="产品" value="产品" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="产品编号" prop="productCode">
                <el-input v-model="editForm.productCode" placeholder="产品编号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="editForm.productName" placeholder="产品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品规格">
                <el-input v-model="editForm.productSpec" placeholder="产品规格" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="报工数" prop="reportedQuantity">
                <el-input-number v-model="editForm.reportedQuantity" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生产人员" prop="productionPersonnel">
                <el-select 
                  v-model="editForm.productionPersonnel" 
                  placeholder="请选择生产人员" 
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="user in userList"
                    :key="user.id"
                    :label="`${user.name} (${user.account})`"
                    :value="user.name"
                  />
                </el-select>
                <!-- 调试信息 -->
                <div style="font-size: 12px; color: #999; margin-top: 4px;">
                  用户数量: {{ userList.length }}
                  <span v-if="userList.length > 0">
                    ({{ userList.slice(0, 3).map(u => u.name).join(', ') }}{{ userList.length > 3 ? '...' : '' }})
                  </span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工序状态" prop="taskStatus">
                <el-radio-group v-model="editForm.taskStatus">
                  <el-radio label="未开始">未开始</el-radio>
                  <el-radio label="进行中">进行中</el-radio>
                  <el-radio label="已完成">已完成</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="单位" prop="unit">
                <el-select v-model="editForm.unit" placeholder="请选择单位" style="width: 100%">
                  <el-option v-for="u in unitOptions" :key="u" :label="u" :value="u" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="良品数" prop="goodQuantity">
                <el-input v-model="editForm.goodQuantity" placeholder="良品数" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="不良品数" prop="defectiveQuantity">
                <el-input v-model="editForm.defectiveQuantity" placeholder="不良品数" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="工序进度">
                <el-input-number 
                  v-model="(editForm as any).processProgress" 
                  :min="0"
                  :max="999999"
                  :step="0.01"
                  placeholder="工序进度"
                  :disabled="!editForm.taskName"
                  controls-position="right"
                  style="width: 100%"
                />
                <div v-if="!editForm.taskName" style="font-size: 12px; color: #999; margin-top: 4px;">请先选择工单与工序名称后再填写工序进度</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="editForm.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="editForm.endTime"
                  type="datetime"
                  placeholder="选择结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="报工时长">
                <div style="display: flex; gap: 10px;">
                  <el-input-number 
                    v-model="editForm.reportDurationHours" 
                    :min="0" 
                    :max="9999"
                    placeholder="小时" 
                    style="width: 80px" 
                    controls-position="right"
                  />
                  <span style="line-height: 32px;">小时</span>
                  <el-input-number 
                    v-model="editForm.reportDurationMinutes" 
                    :min="0" 
                    :max="59"
                    placeholder="分钟" 
                    style="width: 80px" 
                    controls-position="right"
                  />
                  <span style="line-height: 32px;">分钟</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="达标率">
                <el-input v-model="editForm.complianceRate" placeholder="达标率" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="标准效率">
                <el-input v-model="editForm.standardEfficiency" placeholder="标准效率" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="实际效率">
                <el-input v-model="editForm.actualEfficiency" placeholder="实际效率" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- 绩效信息区域 -->
        <div class="form-section">
          <div class="section-header performance-header">绩效信息</div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="计价方式">
                <el-radio-group v-model="editForm.pricingMethod">
                  <el-radio label="计件">计件</el-radio>
                  <el-radio label="计时">计时</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工资单价">
                <el-input v-model="editForm.unitPrice" placeholder="工资单价" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="应奖金额">
                <el-input v-model="editForm.awardAmount" placeholder="应奖金额" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="应罚金额">
                <el-input v-model="editForm.penaltyAmount" placeholder="应罚金额" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- 报工-不良品项区域 -->
        <div class="form-section">
          <div class="section-header defective-header">
            <el-icon><Grid /></el-icon>
            报工-不良品项
          </div>
          <div class="defective-actions">
            <el-button type="primary" size="small" @click="addDefectiveItem">+添加行</el-button>
            <el-button type="danger" size="small" @click="removeDefectiveItem(defectiveItems.length - 1)" :disabled="defectiveItems.length === 0">删除行</el-button>
            <el-button type="danger" size="small" @click="removeSelectedDefectiveItem" :disabled="defectiveItems.length === 0">选择删除</el-button>
            <el-button size="small" @click="importDefectiveItems">导入</el-button>
            <el-button size="small" @click="refreshDefectiveItems">刷新</el-button>
          </div>
          <div class="defective-table">
            <el-table :data="defectiveItems" border style="width: 100%">
              <el-table-column prop="defectiveItem" label="*不良品项" width="200">
                <template #default="scope">
                  <el-select 
                    v-model="scope.row.defectiveItem" 
                    placeholder="请选择不良品项"
                    style="width: 100%"
                    @change="handleDefectiveItemChange(scope.$index)"
                    :loading="loadingDefectiveItems"
                    filterable
                  >
                    <el-option
                      v-for="item in defectiveItemList"
                      :key="item.itemId"
                      :label="`${item.itemCode}|${item.itemName}`"
                      :value="item.itemId"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="*数量" width="150">
                <template #default="scope">
                  <el-input-number 
                    v-model="scope.row.quantity" 
                    :min="0" 
                    style="width: 100%"
                    placeholder="数量"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="150" />
              <el-table-column prop="creator" label="创建人" width="100" />
              <el-table-column prop="modifier" label="修改人" width="100" />
              <el-table-column prop="modifyTime" label="修改时间" width="150" />
            </el-table>
            <div v-if="defectiveItems.length === 0" class="no-data">
              暂无数据
            </div>
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">×关闭</el-button>
          <el-button type="success" @click="handleSave">√保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElTable, ElForm } from 'element-plus'
import { Search, ArrowDown, Refresh, Close, Plus, Grid } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getWorkReportsAdvanced,
  createWorkReport,
  updateWorkReport,
  deleteWorkReport,
  batchDeleteWorkReports,
  exportWorkReports,
  type WorkReport,
  type AdvancedQueryParams,
  type CreateWorkReport,
  type UpdateWorkReport
} from '@/api/workReporting'
import { getWorkOrders, getWorkProcessesByProductId, type WorkOrder } from '@/api/workOrder'
import { getAllUsers, type User } from '@/api/user'
import { MES_XSP_ApiHost, MES_XHY_ApiHost, MES_SMH_ApiHost } from '@/utils/Interceptors'

// 静态选项
const unitOptions = [
  '个','箱','件','套','PCS','只','台','米','条','张','车','天','小时','分钟','周','月'
]

// 响应式数据
const loading = ref(false)
const workReportList = ref<WorkReport[]>([])
const selectedRows = ref<WorkReport[]>([])
const searchKeyword = ref('')
const showAdvancedSearch = ref(false)
const showEditDialog = ref(false)
const isEdit = ref(false)
const editFormRef = ref<FormInstance>()

// 详情抽屉状态
const showDetailDrawer = ref(false)
const detailData = ref<WorkReport | null>(null)

// 不良品项数据
const defectiveItems = ref<any[]>([])

// 加载状态
const loadingWorkOrders = ref(false)
const loadingDefectiveItems = ref(false)

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 30,
  totalCount: 0
})

// 高级查询表单
const advancedSearchForm = reactive({
  pageIndex: 1,
  pageSize: 30,
  taskName: '',
  productCode: '',
  productName: '',
  taskStatus: '',
  productionPersonnel: '',
  reportedQuantity: 0,
  workOrderNo: '',
  unit: '',
  goodQuantity: 0,
  startTimeRange: [],
  endTimeRange: [],
  createTimeRange: []
})

// 编辑表单
const editForm = reactive<CreateWorkReport & { workReportId?: number }>({
  workOrderNo: '',
  taskName: '',
  product: '',
  productCode: '',
  productName: '',
  productSpec: '',
  taskStatus: '进行中',
  productionPersonnel: '',
  reportedQuantity: 0,
  unit: '',
  goodQuantity: 0,
  defectiveQuantity: 0,
  processProgress: '',
  startTime: '',
  endTime: '',
  reportDurationHours: 0,
  reportDurationMinutes: 0,
  complianceRate: '',
  standardEfficiency: '',
  actualEfficiency: '',
  pricingMethod: '计件',
  unitPrice: '',
  awardAmount: '',
  penaltyAmount: '',
  estimatedWage: 0
})

// 表单验证规则
const editRules: FormRules = {
  workOrderNo: [{ required: true, message: '请选择工单', trigger: 'change' }],
  taskName: [{ required: true, message: '请选择工序名称', trigger: 'change' }],
  product: [{ required: true, message: '请选择产品', trigger: 'change' }],
  productCode: [{ required: true, message: '请输入产品编号', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  productionPersonnel: [{ required: true, message: '请选择生产人员', trigger: 'change' }],
  reportedQuantity: [{ required: true, message: '请输入报工数', trigger: 'blur' }],
  unit: [{ required: true, message: '请选择单位', trigger: 'change' }],
  goodQuantity: [{ required: true, message: '请输入良品数', trigger: 'blur' }],
  defectiveQuantity: [{ required: true, message: '请输入不良品数', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

// 页面加载时获取数据
onMounted(async () => {
  console.log('页面加载，开始初始化数据...')
  
  // 清空所有列表数据
  workOrderList.value = []
  defectiveItemList.value = []
  processList.value = []
  userList.value = []
  
  // 获取报工列表
  await loadWorkReports()
  
  // 获取工单列表
  await loadWorkOrders()
  
  // 获取不良品项目列表
  await loadDefectiveItems()
  
  // 获取生产人员列表
  await loadUsers()
  
  console.log('页面初始化完成')
})

// 监听器 - 自动计算预计工资
watch(
  () => [
    editForm.pricingMethod,
    editForm.reportedQuantity,
    editForm.unitPrice,
    editForm.startTime,
    editForm.endTime,
    editForm.awardAmount,
    editForm.penaltyAmount
  ],
  () => {
    calculateEstimatedWage()
  },
  { deep: true }
)

// 监听开始/结束时间，自动校验并计算时长
watch(
  () => [editForm.startTime, editForm.endTime],
  () => {
    if (!editForm.startTime || !editForm.endTime) return
    const start = new Date(editForm.startTime.replace(/-/g, '/'))
    const end = new Date(editForm.endTime.replace(/-/g, '/'))
    if (isNaN(start.getTime()) || isNaN(end.getTime())) return
    // 如果结束时间早于开始时间，自动将结束时间校正为开始时间
    if (end.getTime() < start.getTime()) {
      editForm.endTime = editForm.startTime
    }
    const endFixed = new Date(editForm.endTime.replace(/-/g, '/'))
    const diffMs = endFixed.getTime() - start.getTime()
    if (diffMs >= 0) {
      const totalMinutes = Math.floor(diffMs / 60000)
      editForm.reportDurationHours = Math.floor(totalMinutes / 60)
      editForm.reportDurationMinutes = totalMinutes % 60
    }
  }
)

// 方法
const loadWorkReports = async () => {
  try {
    loading.value = true
    const params: AdvancedQueryParams = {
      ...advancedSearchForm,
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    }
    
    if (searchKeyword.value) {
      params.taskName = searchKeyword.value
    }
    
    const response = await getWorkReportsAdvanced(params)
    if (response.data.code === 200) {
      workReportList.value = response.data.data.items
      pagination.totalCount = response.data.data.totalCount
    } else {
      ElMessage.error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('加载报工数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageIndex = 1
  loadWorkReports()
}

// 切换高级搜索面板
const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
}

const handleAdvancedSearch = () => {
  pagination.pageIndex = 1
  showAdvancedSearch.value = false
  loadWorkReports()
}

const resetAdvancedSearch = () => {
  Object.assign(advancedSearchForm, {
    pageIndex: 1,
    pageSize: 30,
    taskName: '',
    productCode: '',
    productName: '',
    taskStatus: '',
    productionPersonnel: '',
    reportedQuantity: 0,
    workOrderNo: '',
    unit: '',
    goodQuantity: 0,
    startTimeRange: [],
    endTimeRange: [],
    createTimeRange: []
  })
}

const handleSelectionChange = (rows: WorkReport[]) => {
  selectedRows.value = rows
}

const handleRowClick = (row: WorkReport) => {
  openDetail(row)
}

const openDetail = (row: WorkReport) => {
  detailData.value = row
  showDetailDrawer.value = true
}

const handleAdd = () => {
  isEdit.value = false
  resetEditForm()
  showEditDialog.value = true
}

const handleEdit = () => {
  if (selectedRows.value.length !== 1) {
    ElMessage.warning('请选择一条记录进行编辑')
    return
  }
  
  isEdit.value = true
  const row = selectedRows.value[0]
  Object.assign(editForm, row)
  editForm.workReportId = row.workReportId
  showEditDialog.value = true
}

const handleDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '确认删除',
      { type: 'warning' }
    )
    
    if (selectedRows.value.length === 1) {
      const response = await deleteWorkReport(selectedRows.value[0].workReportId)
      if (response.data.code === 200) {
        ElMessage.success('删除成功')
        loadWorkReports()
      } else {
        ElMessage.error(response.data.msg || '删除失败')
      }
    } else {
      const workReportIds = selectedRows.value.map(row => row.workReportId)
      const response = await batchDeleteWorkReports(workReportIds)
      if (response.data.code === 200) {
        ElMessage.success('批量删除成功')
        loadWorkReports()
      } else {
        ElMessage.error(response.data.msg || '批量删除失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleExport = async () => {
  try {
    const params: AdvancedQueryParams = {
      ...advancedSearchForm,
      pageIndex: 1,
      pageSize: pagination.totalCount
    }
    
    if (searchKeyword.value) {
      params.taskName = searchKeyword.value
    }
    
    const response = await exportWorkReports(params)
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `报工数据_${new Date().toISOString().slice(0, 10)}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

const handleSave = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    
    if (isEdit.value) {
      const response = await updateWorkReport(editForm as UpdateWorkReport)
      if (response.data.code === 200) {
        ElMessage.success('更新成功')
        showEditDialog.value = false
        loadWorkReports()
      } else {
        ElMessage.error(response.data.msg || '更新失败')
      }
    } else {
      // 构造后端期望的创建报工数据（直接DTO，无包装），统一数值类型
      const payload: CreateWorkReport = {
        workOrderNo: (editForm.workOrderNo?.toString() || '').trim(),
        taskName: (editForm.taskName?.toString() || '').trim(),
        product: (editForm.product?.toString() || '').trim() || undefined,
        productCode: (editForm.productCode?.toString() || '').trim(),
        productName: (editForm.productName?.toString() || '').trim(),
        productSpec: editForm.productSpec?.toString().trim() || undefined,
        taskStatus: (editForm.taskStatus?.toString() || '进行中').trim(),
        productionPersonnel: (editForm.productionPersonnel?.toString() || '').trim(),
        reportedQuantity: Number(editForm.reportedQuantity) || 0,
        unit: editForm.unit?.toString() || '',
        goodQuantity: Number(editForm.goodQuantity) || 0,
        defectiveQuantity: Number(editForm.defectiveQuantity) || 0,
        processProgress: editForm.processProgress === '' || editForm.processProgress === undefined ? undefined : Number(editForm.processProgress as any),
        startTime: editForm.startTime ? new Date(editForm.startTime as any).toISOString() : undefined,
        endTime: editForm.endTime ? new Date(editForm.endTime as any).toISOString() : undefined,
        reportDurationHours: editForm.reportDurationHours === '' || editForm.reportDurationHours === undefined ? undefined : Number(editForm.reportDurationHours as any),
        reportDurationMinutes: editForm.reportDurationMinutes === '' || editForm.reportDurationMinutes === undefined ? undefined : Number(editForm.reportDurationMinutes as any),
        complianceRate: editForm.complianceRate === '' || editForm.complianceRate === undefined ? undefined : Number(editForm.complianceRate as any),
        standardEfficiency: editForm.standardEfficiency === '' || editForm.standardEfficiency === undefined ? undefined : Number(editForm.standardEfficiency),
        actualEfficiency: editForm.actualEfficiency === '' || editForm.actualEfficiency === undefined ? undefined : Number(editForm.actualEfficiency as any),
        pricingMethod: editForm.pricingMethod || undefined,
        wageUnitPrice: editForm.unitPrice === '' || editForm.unitPrice === undefined ? undefined : Number(editForm.unitPrice),
        awardAmount: editForm.awardAmount === '' || editForm.awardAmount === undefined ? undefined : Number(editForm.awardAmount as any),
        penaltyAmount: editForm.penaltyAmount === '' || editForm.penaltyAmount === undefined ? undefined : Number(editForm.penaltyAmount as any),
        estimatedWage: editForm.estimatedWage === '' || editForm.estimatedWage === undefined ? undefined : Number(editForm.estimatedWage as any)
      }
      // 前置校验：工单号必填
      if (!payload.workOrderNo) {
        ElMessage.error('工单号不能为空')
        return
      }
      // 调试输出，便于排查字段是否正确
      console.log('创建报工提交 payload:', payload)
      const response = await createWorkReport(payload)
      if (response.data.code === 200) {
        ElMessage.success('创建成功')
        showEditDialog.value = false
        loadWorkReports()
      } else {
        ElMessage.error(response.data.msg || '创建失败')
      }
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

const resetEditForm = () => {
  Object.assign(editForm, {
    workOrderNo: '',
    taskName: '',
    product: '',
    productCode: '',
    productName: '',
    productSpec: '',
    taskStatus: '进行中',
    productionPersonnel: '',
    reportedQuantity: 0,
    unit: '',
    goodQuantity: 0,
    defectiveQuantity: 0,
    processProgress: '',
    startTime: '',
    endTime: '',
    reportDurationHours: 0,
    reportDurationMinutes: 0,
    complianceRate: '',
    standardEfficiency: '',
    actualEfficiency: '',
    pricingMethod: '计件',
    unitPrice: '',
    awardAmount: '',
    penaltyAmount: '',
    estimatedWage: 0
  })
  editForm.workReportId = undefined
  defectiveItems.value = []
  processList.value = []
  // userList.value = [] // 不清空生产人员列表，因为这是全局数据
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  loadWorkReports()
}

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  loadWorkReports()
}

const handleBatchApprove = () => {
  ElMessage.info('批量审批功能待实现')
}

const handleRefresh = () => {
  loadWorkReports()
}

// 不良品项相关方法
const addDefectiveItem = () => {
  defectiveItems.value.push({
    defectiveItem: null,
    quantity: 0,
    createTime: new Date().toLocaleString('zh-CN'),
    creator: '当前用户',
    modifier: '',
    modifyTime: ''
  })
}

const removeDefectiveItem = (index: number) => {
  if (index >= 0 && index < defectiveItems.value.length) {
    defectiveItems.value.splice(index, 1)
  }
}

const removeSelectedDefectiveItem = () => {
  // 这里可以实现选择删除的逻辑
  if (defectiveItems.value.length > 0) {
    removeDefectiveItem(defectiveItems.value.length - 1)
  }
}

const importDefectiveItems = () => {
  ElMessage.info('导入功能待实现')
}

const refreshDefectiveItems = () => {
  loadDefectiveItems()
}

// 工单相关数据和方法
const workOrderList = ref<Array<{
  workOrderNo: string
  workOrderName: string
  workOrderData: WorkOrder
}>>([])

const defectiveItemList = ref<Array<{
  itemId: number
  itemName: string
  itemCode: string
}>>([])

// 工序列表数据
const processList = ref<Array<{
  processId: number
  processName: string
  processCode: string
}>>([])

// 生产人员列表数据
const userList = ref<Array<User>>([])

// 获取工单列表
const loadWorkOrders = async () => {
  try {
    loadingWorkOrders.value = true
    
    console.log('开始获取工单列表...')
    const response = await getWorkOrders({
      pageIndex: 1,
      pageSize: 1000 // 获取所有工单
    })
    
    console.log('工单API响应:', response)
    
    if (response.data.code === 200) {
      console.log('工单数据:', response.data.data)
      workOrderList.value = response.data.data.items.map(workOrder => ({
        workOrderNo: workOrder.orderNo || '',
        workOrderName: workOrder.taskName || workOrder.product || '未命名工单',
        workOrderData: workOrder // 保存完整的工单数据
      }))
      console.log('处理后的工单列表:', workOrderList.value)
    } else {
      console.error('工单API返回错误:', response.data)
      ElMessage.error(response.data.msg || '获取工单列表失败')
      workOrderList.value = []
    }
    
  } catch (error) {
    console.error('获取工单列表失败:', error)
    ElMessage.error('获取工单列表失败')
    workOrderList.value = []
  } finally {
    loadingWorkOrders.value = false
  }
}

// 获取不良品项目列表（来自 SMH 网关）
const loadDefectiveItems = async () => {
  try {
    loadingDefectiveItems.value = true
    const resp = await MES_SMH_ApiHost.get('/api/DefectItem/GetAllDefectItems')
    if (resp.data?.code === 200) {
      const list = Array.isArray(resp.data.data) ? resp.data.data : []
      defectiveItemList.value = list
        .filter((x: any) => x && x.isDelete !== true)
        .map((x: any) => ({
          itemId: x.defectItemId ?? x.itemId ?? 0,
          itemCode: x.defectCode ?? x.itemCode ?? '',
          itemName: x.defectName ?? x.itemName ?? ''
        }))
    } else {
      ElMessage.error(resp.data?.msg || '获取不良品项失败')
      defectiveItemList.value = []
    }
  } catch (error) {
    console.error('获取不良品项目失败:', error)
    ElMessage.error('获取不良品项失败，请检查网络或服务')
    defectiveItemList.value = []
  } finally {
    loadingDefectiveItems.value = false
  }
}

// 获取生产人员列表
const loadUsers = async () => {
  try {
    const response = await getAllUsers()
    
    if (response.data.code === 200) {
      // 映射字段名：后端返回大写开头，前端期望小写开头
      const mappedUsers = response.data.data.map((user: any) => ({
        id: user.Id || user.id,
        account: user.Account || user.account,
        name: user.Name || user.name,
        role: user.Role || user.role,
        isActive: user.IsActive !== undefined ? user.IsActive : user.isActive,
        organizationStructure: user.OrganizationStructure || user.organizationStructure,
        remark: user.Remark || user.remark,
        avatar: user.Avatar || user.avatar,
        gender: user.Gender || user.gender
      }))
      
      // 过滤出可用的用户（isActive = true）
      userList.value = mappedUsers.filter(user => user.isActive)
    } else {
      ElMessage.error(response.data.msg || '获取生产人员列表失败')
      userList.value = []
    }
    
  } catch (error: any) {
    console.error('获取生产人员列表失败:', error)
    ElMessage.error('获取生产人员列表失败')
    userList.value = []
  }
}

// 工单选择变化处理
const handleWorkOrderChange = async (workOrderNo: string) => {
  console.log('工单选择变化:', workOrderNo)
  if (!workOrderNo) {
    // 清空相关字段
    editForm.taskName = ''
    editForm.product = ''
    editForm.productCode = ''
    editForm.productName = ''
    editForm.productSpec = ''
    editForm.unit = ''
    editForm.standardEfficiency = ''
    editForm.actualEfficiency = ''
    processList.value = []
    return
  }
  
  // 根据选择的工单自动填充相关信息
  const selectedWorkOrder = workOrderList.value.find(wo => wo.workOrderNo === workOrderNo)
  if (selectedWorkOrder && selectedWorkOrder.workOrderData) {
    const workOrderData = selectedWorkOrder.workOrderData
    
    // 使用真实的工单数据自动填充
    editForm.product = workOrderData.product || ''
    editForm.productCode = workOrderData.productCode || ''
    editForm.productName = workOrderData.productName || ''
    editForm.productSpec = workOrderData.productSpec || ''
    editForm.unit = workOrderData.unit || ''
    editForm.standardEfficiency = workOrderData.standardEfficiency?.toString() || ''
    editForm.actualEfficiency = workOrderData.actualEfficiency?.toString() || ''
    
    // 根据选择的工单获取对应的工序列表
    await loadProcessesByWorkOrder(workOrderNo)
  }
}

// 根据工单获取对应的工序列表
const loadProcessesByWorkOrder = async (workOrderNo: string) => {
  try {
    console.log('开始获取工单对应的工序列表:', workOrderNo)
    
    // 立即清空工序列表，避免显示旧数据
    processList.value = []
    console.log('工序列表已清空')
    
    // 获取选择的工单信息
    const selectedWorkOrder = workOrderList.value.find(wo => wo.workOrderNo === workOrderNo)
    if (!selectedWorkOrder || !selectedWorkOrder.workOrderData.productId) {
      console.log('工单数据中没有产品ID，无法获取工序列表')
      console.log('工单数据:', selectedWorkOrder?.workOrderData)
      processList.value = []
      return
    }
    
    const productId = selectedWorkOrder.workOrderData.productId
    console.log('使用产品ID获取工序列表:', productId)
    console.log('完整工单数据:', selectedWorkOrder.workOrderData)
    
    // 调用API获取产品对应的工序列表
    console.log('调用API: getWorkProcessesByProductId(', productId, ')')
    const response = await getWorkProcessesByProductId(productId)
    console.log('工序API响应:', response)
    
    if (response && response.data && response.data.code === 200) {
      const processes = response.data.data
      console.log('API返回的原始工序数据:', processes)
      
      processList.value = processes.map(process => ({
        processId: process.workProcessId,
        processName: process.processName,
        processCode: process.processCode
      }))
      console.log('处理后的工序列表:', processList.value)
    } else {
      console.log('API返回错误，使用工单数据中的工序信息作为备选')
      console.log('API响应详情:', response)
      
      // 如果API调用失败，使用工单数据中的工序信息作为备选
      if (selectedWorkOrder.workOrderData.taskName) {
        processList.value = [{
          processId: 1,
          processName: selectedWorkOrder.workOrderData.taskName,
          processCode: 'PROC001'
        }]
        console.log('使用备选工序数据:', processList.value)
      } else {
        processList.value = []
        console.log('没有备选工序数据')
      }
    }
    
  } catch (error) {
    console.error('获取工序列表失败:', error)
    
    // 如果API调用失败，使用工单数据中的工序信息作为备选
    const selectedWorkOrder = workOrderList.value.find(wo => wo.workOrderNo === workOrderNo)
    if (selectedWorkOrder && selectedWorkOrder.workOrderData.taskName) {
      processList.value = [{
        processId: 1,
        processName: selectedWorkOrder.workOrderData.taskName,
        processCode: 'PROC001'
      }]
      console.log('异常情况下使用备选工序数据:', processList.value)
    } else {
      processList.value = []
      console.log('异常情况下没有备选工序数据')
    }
  }
}

// 不良品项选择变化处理
const handleDefectiveItemChange = (index: number) => {
  const selectedItem = defectiveItemList.value.find(item => item.itemId === defectiveItems.value[index].defectiveItem);
  if (selectedItem) {
    defectiveItems.value[index].defectiveItem = selectedItem.itemId;
  }
};

// 计算预计工资
const calculateEstimatedWage = () => {
  if (editForm.pricingMethod === '计件') {
    editForm.estimatedWage = (editForm.reportedQuantity || 0) * (editForm.unitPrice || 0)
  } else if (editForm.pricingMethod === '计时') {
    // 计时工资计算逻辑
    const startTime = new Date(editForm.startTime || '')
    const endTime = new Date(editForm.endTime || '')
    if (startTime && endTime && startTime < endTime) {
      const hours = (endTime.getTime() - startTime.getTime()) / (1000 * 60 * 60)
      editForm.estimatedWage = hours * (editForm.unitPrice || 0)
    }
  }
  
  // 加上奖励金额，减去处罚金额
  editForm.estimatedWage += (editForm.awardAmount || 0) - (editForm.penaltyAmount || 0)
}

// 工具方法
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

const getTaskNameTagType = (taskName: string) => {
  const typeMap: Record<string, string> = {
    '维修': 'danger',
    '破损': 'warning',
    '金涂料': 'success',
    '焊接': 'info'
  }
  return typeMap[taskName] || 'info'
}

const getTaskStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    '已完成': 'success',
    '进行中': 'warning',
    '暂停': 'info'
  }
  return typeMap[status] || 'info'
}

const getComplianceRateClass = (rate: number) => {
  if (rate >= 100) return 'text-success'
  if (rate >= 80) return 'text-warning'
  return 'text-danger'
}

const formatComplianceRate = (rate: number) => {
  if (isNaN(rate) || rate === 0) return '0.00%'
  return `${rate.toFixed(2)}%`
}
</script>

<style scoped>
.work-reporting-container {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.page-title {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 15px;
  align-items: center;
}

.header-actions .add-btn {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
  border: none;
  color: white;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 120px;
}

.header-actions .add-btn:hover {
  background: linear-gradient(135deg, #5daf34 0%, #529b2e 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.table-container {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
  position: relative;
  max-height: calc(100vh - 200px);
}

.table-pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 15px 20px;
  background: #f5f7fa;
  border-top: 1px solid #e4e7ed;
  flex-shrink: 0;
  position: relative;
  z-index: 10;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.text-danger {
  color: #f56c6c;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-input) {
  border-radius: 6px;
}

:deep(.el-select) {
  border-radius: 6px;
}

:deep(.el-date-picker) {
  border-radius: 6px;
}

:deep(.el-input-number) {
  border-radius: 6px;
}

/* 高级查询面板样式 */
.advanced-search-panel {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  padding: 20px;
}

.advanced-search-form {
  margin-bottom: 0;
}

.advanced-search-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.search-btn {
  min-width: 100px;
}

.reset-btn {
  min-width: 100px;
}

.close-btn {
  min-width: 100px;
}

.add-btn {
  min-width: 120px;
  background: linear-gradient(135deg, #409eff 0%, #36a3f7 100%);
  border: none;
  color: white;
  font-weight: 500;
  transition: all 0.3s ease;
}

.add-btn:hover {
  background: linear-gradient(135deg, #36a3f7 0%, #2d8cf0 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 新增对话框样式 */
:deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #409eff 0%, #36a3f7 100%);
  color: white;
  border-radius: 12px 12px 0 0;
  padding: 20px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-dialog__body) {
  padding: 30px;
}

:deep(.el-dialog__footer) {
  padding: 20px 30px;
  border-top: 1px solid #e4e7ed;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.work-report-dialog .el-form-item__label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.work-report-dialog .el-form-item.is-required .el-form-item__label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.work-report-dialog .el-form-item.is-success .el-form-item__label::before {
  content: '';
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 新增对话框自定义样式 */
.work-report-dialog .el-dialog__body {
  padding: 20px; /* 减少内边距 */
}

.work-report-dialog .el-dialog__header {
  padding: 15px 20px; /* 减少内边距 */
}

.work-report-dialog .el-dialog__title {
  font-size: 16px; /* 减小标题字体 */
}

.work-report-dialog .el-dialog__footer {
  padding: 15px 20px; /* 减少内边距 */
}

.work-report-dialog .el-form-item {
  margin-bottom: 15px; /* 减小表单项间距 */
}

.work-report-dialog .el-form-item__label {
  font-size: 14px; /* 减小标签字体 */
}

.work-report-dialog .el-input__wrapper {
  font-size: 14px; /* 减小输入框字体 */
}

.work-report-dialog .el-select .el-input__wrapper {
  font-size: 14px;
}

.work-report-dialog .el-date-picker .el-input__wrapper {
  font-size: 14px;
}

.work-report-dialog .el-input-number .el-input__wrapper {
  font-size: 14px;
}

.work-report-dialog .el-radio-group {
  display: flex;
  gap: 20px;
  align-items: center;
}

.work-report-dialog .el-radio-group .el-radio {
  font-size: 14px;
}

.work-report-dialog .el-form-item__content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.work-report-dialog .el-form-item__content .el-input,
.work-report-dialog .el-form-item__content .el-select,
.work-report-dialog .el-form-item__content .el-date-picker,
.work-report-dialog .el-form-item__content .el-input-number {
  flex: 1;
}

.work-report-dialog .el-form-item__content .el-button {
  flex-shrink: 0;
}

.work-report-dialog .form-section {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
}

.work-report-dialog .section-header {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.work-report-dialog .section-header .el-icon {
  margin-right: 8px;
  font-size: 20px;
  color: #409eff;
}

.work-report-dialog .performance-header .el-icon {
  color: #67c23a;
}

.work-report-dialog .performance-header {
  background: linear-gradient(135deg, #20b2aa 0%, #48cae4 100%);
  color: white;
  padding: 10px 15px;
  border-radius: 6px;
  margin: -20px -20px 15px -20px;
  border: none;
}

.work-report-dialog .performance-header::before {
  content: '';
}

.work-report-dialog .defective-header .el-icon {
  color: #e6a23c;
}

.work-report-dialog .defective-header {
  background: linear-gradient(135deg, #ffa726 0%, #ffb74d 100%);
  color: white;
  padding: 10px 15px;
  border-radius: 6px;
  margin: -20px -20px 15px -20px;
  border: none;
}

.work-report-dialog .defective-header::before {
  content: '';
}

.work-report-dialog .defective-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.work-report-dialog .defective-table {
  border: 1px solid #ebeef5;
  border-radius: 6px;
  overflow: hidden;
}

.work-report-dialog .defective-table .el-table {
  border-radius: 0;
}

.work-report-dialog .defective-table .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.work-report-dialog .defective-table .el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}

.work-report-dialog .defective-table .el-table__body tr:hover > td {
  background-color: #f5f7fa;
}

.work-report-dialog .defective-table .el-table__empty-text {
  font-size: 14px;
  color: #909399;
}

.work-report-dialog .defective-table .el-select {
  width: 100%;
}

.work-report-dialog .defective-table .el-input-number {
  width: 100%;
}

.work-report-dialog .defective-table .el-table td {
  padding: 8px;
}

.work-report-dialog .defective-table .el-table .el-select .el-input__wrapper {
  border: none;
  box-shadow: none;
}

.work-report-dialog .defective-table .el-table .el-input-number .el-input__wrapper {
  border: none;
  box-shadow: none;
}

.work-report-dialog .no-data {
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}
</style>
